/* 配置 */
// var UC_PATH_ = "/tmooc"; // 用户中心API接口前缀 例如 :http://xxx.com/[包名]
var UC_PATH_ = "http://uc.tmooc.cn"; // 用户中心API接口前缀 例如 :http://xxx.com/[包名]
var TTS_MYTTS_URL = "http://tts.tmooc.cn"; // TTS 线上
//var TTS_MYTTS_URL = "http://test.tmooc.cn/tts-front-web"; // TTS 测试环境
var www_path ="http://www.tmooc.cn";
//登录成功回调方法 队列；使用方法： window.loginSuccessCallback.add(fn);
window.loginSuccessCallback = $.Callbacks();
//退出成功回调方法 队列；使用方法： window.logoutSuccessCallback.add(fn);
window.logoutSuccessCallback = $.Callbacks();
var pageUrl;
// 全局ajax设置

$.ajaxSetup({
    headers: {
        'X-Requested-With': 'XMLHttpRequest'
    },
    xhrFields: {
        withCredentials: true
    },
    cache: false
});

/* 公共方法 */
/* tab标签 demo-test @lianglei */
$.fn.cusTab = function (opt) {
    var tabs_ = this.find('[data-module="tab"]');
    tabs_.on('click', function () {
        if ($(this).hasClass('active')) {
            return false;
        }
        tabs_.removeClass('active');
        $(this).addClass('active');
        var target_ = $('#' + $(this).data('target'));
        target_.addClass('active');
        target_.siblings('.tab-item').removeClass('active');
        if ($.type(opt) == 'object' && $.type(opt.callback) == 'function') {
            opt.callback(tabs_, target_);
        }

    });
};

// 获取指定 cookie
function getCookie(name) {
    var arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");
    if (arr = document.cookie.match(reg)) {
        return unescape(arr[2]);
    } else {
        return '';
    }
}

// 获取hash
function get_hash(strName) {
    var strHref = window.location.hash;
    var intPos = strHref.indexOf('#');
    var strRight = strHref.substr(intPos + 1);
    var arrTmp = strRight.split('&');
    for (var i = 0; i < arrTmp.length; i++) {
        var arrTemp = arrTmp[i].split('=');
        if (arrTemp[0].toUpperCase() == strName.toUpperCase() && arrTemp[1]) {
            if (i === arrTmp.length - 1) {
                var sIndex = arrTemp[1].indexOf('#');
                if (sIndex !== -1) {
                    arrTemp[1] = arrTemp[1].substring(0, sIndex);
                }
            }
            return arrTemp[1];
        }
    }
    return '';
}

// 写入hash
function set_hash(str) {
    if (str && typeof(str) == "string") {
        window.location.hash = '#' + str;
    }
}


/*验证类型*/
function checkType(str, type, obj, form) {
    switch (type) {
        case 'required':
            /*必填*/
            return (str != '');
        case 'mail':
            return /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/.test(str);
        case 'phone':
            /*手机号验证,支持台湾*/
            return /^((?!1{11})1\d{10}|09\d{8})$/.test(str);
        case 'mail_phone':
            return /^(\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*|(?!1{11})1\d{10}|09\d{8})$/.test(str);
        case 'code':
            return (function () {
                var num = obj.attr('cuslength') || 1;
                var str_ = '^[0-9]{' + num + '}$';
                var reg = new RegExp(str_);
                return reg.test(str);
            })();
        case 'code_en':
            return (function () {
                var num = obj.attr('cuslength') || 1;
                var str_ = '^[0-9a-zA-Z]{' + num + '}$';
                var reg = new RegExp(str_);
                return reg.test(str);
            })();
        case 'chinese':
            return /^[\u4E00-\u9FA5]+$/.test(str);
        case 'ch_and_en':
            /*姓名验证*/
            return /^[a-zA-Z\u4E00-\u9FA5]+$/.test(str);
        case 'nickname':
            return (function () {
                var num = obj.attr('cuslength') || '4,12';
                var str_ = '^[[0-9a-zA-Z_\u4E00-\u9FA5]{' + num + '}$';
                var reg = new RegExp(str_);
                return reg.test(str);
            })();
        //return /^[0-9a-zA-Z_\u4E00-\u9FA5]{4,12}$/.test(str);
        case 'qq':
            /*QQ*/
            return /^[0-9]{5,11}$/.test(str);
        case 'pwd':
            return /^[0-9a-zA-Z_]{6,18}$/.test(str);
        case 'equalTo':
            return (function () {
                var tar = obj.attr('equalTo');
                return (str === $.trim(form.find('#' + tar).val()));
            })();
        case 'specialchars':
            return !/[\-\_\,\!\|\~\`\(\)\#\$\%\^\&\*\{\}\:\;\"\<\>\?]/g.test(str);
        default:
            return true;
    }
}

function validateForm(form_id, opt) {
    var form_ = $('#' + form_id);
    if (!form_.length) {
        return false;
    }
    var fnObj = $.extend(true, {
        checkform: function (obj, val, type) {
            if (type == 'select' || type == 'radio_checkbox') {
                obj.off('change.cusrule').on('change.cusrule', function () {
                    fnObj.errtips($(this), $.trim(this.value), $(this).attr('cusrule'));
                });
            } else {
                obj.off('blur.cusrule').on('blur.cusrule', function () {
                    fnObj.errtips($(this), $.trim(this.value), $(this).attr('cusrule'));
                });
            }
            return this.errtips(obj, val, type);
        },
        form: function () {
            var param = true;
            form_.find('input[cusrule], select[cusrule], textarea[cusrule], div[cusrule]').each(function (i, n) {
                var obj = $(n);
                var cur = fnObj.checkform(obj, $.trim(this.value), obj.attr('cusrule'));
                param = (param && cur);
            });
            return param;
        },
        errtips: function (obj, val, type) {
            var res = checkType(val, type, obj, form_);
            !res ? obj.closest('.form-inp-area').addClass('error') : obj.closest('.form-inp-area').removeClass('error');
            return res;
        }
    }, opt);

    return fnObj;
}

/*登录弹框-xxw*/
$('#login_xxw').click(function () {
    if (window.IS_UC_PAGE_) { //用户中心页面登录
        location.href = UC_PATH_ + '/login/jumpTologin';
    } else {
        toLoginWinFn();
    }
    return false;
});

/* 登陆弹窗方法 */
function toLoginWinFn() {
    $.colorbox({
        speed: 0,
        inline: true,
        overlayClose: false,
        close: false,
        href: "#login_boxxxw",
        onOpen: function () {
            $('#js_login_form').find('.error').removeClass('error');
            $('.js-md-180417-login-cj').find('.js-log-type:first').show()
                .siblings('.js-log-type').hide();
            $('#js_account_pm, #js_password, #js_imgcode').val('');
            $('#js_submit_login').data('isclick', false).html('登录');
        }
    });
    refreshValidateImg(); //刷新验证码
}

/* ccj */

// 图片验证码
function refreshValidateImg(ele) {
    $('#' + (ele || 'js_validate_img')).attr("src", UC_PATH_ + "/validateCode?t=" + Math.random());
}

// 发送短信、邮箱验证码
function sendValidateCode(opt) {
    if ($.type(opt) != 'object' || !opt.obj.length) {
        return false;
    }
    var $obj = opt.obj;
    if (!$obj.data('issend')) {
        var second = opt.time || 59;
        var s_time = setInterval(function () {
            if (second <= 1) {
                $obj.prop('disabled', false).data('issend', false).text(opt.txt || '获取动态码');
                clearInterval(s_time);
                return false;
            } else {
                $obj.text('（' + second-- + 's）');
            }
        }, 1000);

        $.post(opt.url, opt.data, function (res) {
            if (res.code != 1) {
                $obj.prop('disabled', false).data('issend', false).text(opt.txt || '获取动态码');
                clearInterval(s_time);
                layer.msg(res.msg);
            }
            opt.callback && opt.callback(res);
        });
        $obj.prop('disabled', true).data('issend', true);
    }
}

// 初始化登录
function initLoginFn() {
    // refreshValidateImg();

    $('.js-validate-img').click(function () {
        refreshValidateImg();
    });
    // 登录类型切换
    $('.js-md-180417-login-cj').on('click', '.js-log-type-cut', function () {
        var p_ = $(this).closest('.js-log-type');
        p_.hide().siblings('.js-log-type').show();

        var sib_ = p_.siblings('.js-log-type');
        if (sib_.data('logtype') == 3) {
            var state;
            if (window.IS_UC_PAGE_) {
                state = window.IS_UC_PAGE_;
            } else {
                var local = location.href;
                state = encodeURIComponent(encodeURIComponent(local));
            }
            if (window.WxLogin) {
                new WxLogin({
                    self_redirect: false,
                    id: "js_wx_code_log",
                    appid: "wx3478ef3576df5109",
                    scope: "snsapi_login",
                    redirect_uri: encodeURIComponent("http://www.tmooc.cn/touc" + "/login/wxLogin"),
                    state: state,
                    style: "black",
                    href: ""
                });
            } else {
                $('#js_wx_code_log').html('<p style="font-size: 16px; padding-top: 50px;">微信初始化失败，请重试！</p>');
            }

        }
        setTimeout(function () {
            $.colorbox && $.colorbox.resize();
        }, 10);
    });
    // 提交表单-登录
    $(document).on('click','#js_submit_login',function(){
    //$('#js_submit_login').click(function () {
        if (validateForm('js_login_form').form()) {
            var t_ = $(this);

            var loginNmae = $.trim($('#js_account_pm').val());
            var password = $.trim($('#js_password').val());
            var imgcode = $.trim($('#js_imgcode').val());
            var log_type; // 0 手机，1 邮箱

            var flag_ = true;

            // 用户名类型判断
            if (checkType(loginNmae, 'mail')) {
                log_type = 1;
            } else if (checkType(loginNmae, 'phone')) {
                log_type = 0;
            }

            if (!t_.data('isclick')) {
                t_.data('isclick', true).html('登录中...');
                // 登录次数
                $.post(UC_PATH_ + "/login/loginTimes", {
                    loginName: loginNmae,
                    accountType: log_type
                }, function (res) {
                    if (res.code == 1) {
                        if (res.obj >= 3) {
                            if (!$('#js_validate_img_area').is(':visible')) {
                                $('#js_validate_img_area').show().find('#js_imgcode').attr('cusrule', 'code_en').attr('cuslength', 4);
                                $.colorbox.resize();
                                flag_ = false;
                                refreshValidateImg();
                            }
                            t_.data('isclick', false).html('登录');
                        }
                        if (flag_) {
                            // 登录接口
                            $.post(UC_PATH_ + "/login", {
                                loginName: loginNmae,
                                password: MD5(password),
                                imgCode: imgcode,
                                accountType: log_type
                            }, function (res) {
                                // TODO
                                // TTS 用户要有提示信息
                                if (res.code == 1 || res.code == 2) {
                                    if (window.IS_UC_PAGE_) { //用户中心页面登录，跳转到个人中心首页
                                        location.href = UC_PATH_ + "/userCenter/toUserCenterPage";
                                        return false;
                                    } else { //门户网站 关闭弹窗
                                        layer.msg('登录成功');
                                        getUserLoginStatus(); //更新tobbar状态
                                        var domain = window.location.href;
                                        if (domain == 'http://www.tmooc.cn/') {
                                            checkUserSpecial();
                                            MyCourse();
                                        }
                                        window.loginSuccessCallback.fire(res); //登录成功回调
                                    }
                                    if (res.code == 2) {
                                        /*TTS用户验证提醒*/
                                        $.colorbox({
                                            speed: 0,
                                            inline: true,
                                            overlayClose: false,
                                            close: false,
                                            href: "#js_yz_video"
                                        });
                                    } else {
                                        $.colorbox && $.colorbox.close();
                                    }
                                } else if (res.code == -8009) {
                                    // 未激活
                                    $('#js_account_pm').before('<a href="http://uc.tmooc.cn/login/jumpToActiveMailobx" style="position: absolute;top: -17px;font-size: 12px;">该账号未激活，<span style="color:red">点击去激活</span></a>');
                                } else if (res.code == -9001) {
                                    // 禁用
                                    layer.msg(res.msg);
                                } else {
                                    layer.msg(res.msg);
                                    refreshValidateImg();
                                }
                                t_.data('isclick', false).html('登录');

                            });
                        }
                    } else {
                        t_.data('isclick', false).html('登录');
                        layer.msg(res.msg);
                    }
                });
            }

        }
    });
    $('#js_password, #js_imgcode').keypress(function (e) {
        if (e.keyCode === 13) {
            $('#js_submit_login').trigger('click');
        }
    });
}

// 注册初始化
function initRegisterFn() {
    refreshValidateImg();
    $('.js-validate-img').click(function () {
        var $img = $(this).closest('.form-inp-area').find('img');
        refreshValidateImg($img.attr('id'));
    });
    // 切换tab
    $('#md_2018040401_ll').cusTab({
        callback: function (tabs_, target_) {
            if (target_.attr('id') == 'md_2018040401_ll_tab2') {
                refreshValidateImg('js_validate_img_m');
            } else {
                refreshValidateImg();
            }
        }
    });

    // 注册 方法
    function register(obj, type, loginName, password, nickName, validateCode) {
        if (!obj.data('issend')) {
            $.post(UC_PATH_ + "/user/registerAccount", {
                loginName: loginName,
                password: password,
                nickName: nickName,
                validateCode: validateCode,
                accountType: type
            }, function (res) {
                if (res.code != 1) {
                    obj.data('issend', false);
                    refreshValidateImg((type == 1 && 'js_validate_img_m'));
                    layer.msg(res.msg);
                } else {
                    if (window.IS_UC_PAGE_) { //用户中心页面登录，跳转到个人中心首页
                        layer.msg('注册成功,3s后跳转登录页');
                        setTimeout(function () {
                            location.href = UC_PATH_ + '/login/jumpTologin';
                        }, 3000);
                    } else {
                        $.colorbox && $.colorbox.close();
                        getUserLoginStatus(); //更新tobbar状态
                    }
                }
                window.registerSuccessCallback && window.registerSuccessCallback(res);
            });
            obj.data('issend', true);
        }
    }

    // 手机 动态验证码
    $('#js_DynamicCodePhone').click(function () {
        var t_ = $(this);
        var reg_account = $.trim($('#js_account_phone').val());
        var img_code = $.trim($('#js_imgcode_phone').val());

        var v_account = validateForm('js_reg_phone_form').checkform($('#js_account_phone'), reg_account, 'phone');
        var v_imgCode = validateForm('js_reg_phone_form').checkform($('#js_imgcode_phone'), img_code, 'code_en');

        if (v_account && v_imgCode) {
            sendValidateCode({
                obj: t_,
                url: UC_PATH_ + "/user/sendPhoneCode",
                data: {
                    phone: reg_account,
                    imgCode: img_code
                }
            });
        }
    });
    // 邮箱 动态验证码
    $('#js_DynamicCodeEmail').click(function () {
        var t_ = $(this);
        var reg_account = $.trim($('#js_account_mail').val());
        var img_code = $.trim($('#js_imgcode_mail').val());

        var v_account = validateForm('js_reg_mail_form').checkform($('#js_account_mail'), reg_account, 'mail');
        var v_imgCode = validateForm('js_reg_mail_form').checkform($('#js_imgcode_mail'), img_code, 'code_en');

        if (v_account && v_imgCode) {
            sendValidateCode({
                obj: t_,
                url: UC_PATH_ + "/user/sendEmail",
                data: {
                    email: reg_account,
                    imgCode: img_code
                }
            });
        }
    });
    // 手机 注册
    $('#js_submit_reg_phone').click(function () {
        if (!$('#js_form_user_regyx').is(':checked')) {
            layer.msg('请阅读并勾选同意用户注册协议！');
            return false;
        }
        if (validateForm('js_reg_phone_form').form()) {
            var account = $.trim($('#js_account_phone').val());
            var pwd = $.trim($('#js_pwd_phone2').val());
            var img_code = $.trim($('#js_imgcode_phone').val());
            var dy_code = $.trim($('#js_dy_code_phone').val());

            register($(this), 0, account, pwd, '', dy_code);
        }
    });
    // 邮箱 注册
    $('#js_submit_reg_mail').click(function () {
        if (!$('#js_form_user_regyx').is(':checked')) {
            layer.msg('请阅读并勾选同意用户注册协议！');
            return false;
        }
        if (validateForm('js_reg_mail_form').form()) {
            var account = $.trim($('#js_account_mail').val());
            var name = $.trim($('#js_name_mail').val());
            var pwd = $.trim($('#js_pwd_mail2').val());
            var img_code = $.trim($('#js_imgcode_mail').val());
            var dy_code = $.trim($('#js_dy_code_mail').val());

            register($(this), 1, account, pwd, name, dy_code);
        }
    });
    $('#js_dy_code_phone').keypress(function (e) {
        if (e.keyCode === 13) {
            $('#js_submit_reg_phone').trigger('click');
        }
    });
    $('#js_dy_code_mail').keypress(function (e) {
        if (e.keyCode === 13) {
            $('#js_submit_reg_mail').trigger('click');
        }
    });
}

//提交验证码
function submitValidCode(courseversion,studymode,studentClassroomId) {
    $('.error-lty span').html('');//清空错误信息
    //
    //获取用户输入的信息
    var inputCode = $("#inputCode").val();
    if (inputCode.length != 6) {
        $('.error-lty span').html('请输入6位验证码');
        return;
    }
    //获取到sessionid,courseName,phone,courseCode,相关信息
    var param = getCourseValidInfo();
    param.code = inputCode;
    //发送异步请求获取相关数据
    $('#submitValidId').prop("disabled", true);//按钮置灰
    $.ajax({
        type: "POST",
        url: UC_PATH_ + "/userValidate/doValidateCode",
        data: param,
        dataType: "json",
        success: function (result) {
            if (result.code == 0) {
                $('.error-lty span').html(result.msg);
            }
            if (result.code == 1) {//发送成功
                $('.error-lty span').html('验证成功,5秒后自动跳转...');
                removeCourseValidInfo();
                setTimeout(function () {
                	if(courseversion || studymode){
                		//跳转到tts教历页
                		checkTtsUser(courseversion,studentClassroomId);
                	}else{
                		//刷新当前页
                		window.location.reload();
                		
                	}
                }, 5000);

            }else{
            	 $('#submitValidId').prop("disabled", false);//按钮置灰
            }
        },
        error: function () {
            console.info("error");
        }
    });
}

//输入框关闭的时候清空绑定的数据
function closeCancel() {
    //removeCourseValidInfo();
}

function doUserValidate(obj) {
    $('.error-lty span').html('');//清空错误信息
    $("#inputCode").val('');//清空数据
    appendHtml();
    $('#courseName').val($(obj).parent().parent().data("courseName"));
    $('#phone').val($(obj).parent().parent().data("phone"));
    if (second <= 0) {
        $('#submitValidId').prop("disabled", false);//按钮复位
    }
    //获取到sessionid,courseName,phone,courseCode,相关信息
    //绑定到该该框中，courseInfoId
    $("#courseInfoId").data("courseName", $(obj).parent().parent().data("courseName"));
    $("#courseInfoId").data("phone", $(obj).parent().parent().data("phone"));
    $("#courseInfoId").data("courseCode", $(obj).parent().parent().data("courseCode"));
}

function courseValidate() {

    $.colorbox({
        speed: 0,
        inline: true,
        overlayClose: false,
        close: false,
        href: "#tk-box",

    });
}

function enterCourse(result) {
    window.open(pageUrl);
}


function checkUserSpecial() {
    $.ajax({
        type: "POST",
        url: UC_PATH_ + "/user/checkUserSpecial",
        dataType: "json",
        success: function (result) {
            if (result.code == 1) {//是特色学员，但是未转化
                $('body').append('<img class="fixed-0313img" id="specialCourse" onclick="specialCourse()" src="http://cdn.tmooc.cn/tmooc-web/css/img/enter_course.png"/>');
            }
        },
        error: function () {
            console.info("error");
        }
    });

}